package com.uiotsoft.util.encrypt;

import java.security.MessageDigest;

public class MD5Utils {
	private static final String hexDigIts[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};

	public static String MD5Encoding(String origin,String charsetName ) {
		String result = "";
		try {
			MessageDigest md5 =  MessageDigest.getInstance("MD5");
			if(charsetName == null || charsetName.equals("")) {
				result = byteArrayToHexString(md5.digest(origin.getBytes()));
			}else {
				result = byteArrayToHexString(md5.digest(origin.getBytes(charsetName)));
			}
		}catch(Exception e) {

		}
		return result;

	}

	public static String byteArrayToHexString(byte[] b) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i]&0xff);
			if(hex.length()==1) {
				hex = '0'+hex;
			}
			sb.append(hex);
		}
		return sb.toString();
	}

	public static String byteToHexString(byte b) {
		int n = b;
		if(n<0) {
			n += 256;
		}
		int d1 = n/16;
		int d2 = n%16;
		return hexDigIts[d1]+hexDigIts[d2];
	}

	public static String byteToHex(byte b) {
		String hex = Integer.toHexString(b&0xff);
		if(hex.length()==1) {
			hex = '0'+hex;
		}
		return hex;
	}
}


